var fs = require('fs');
var config = require('../config.json');
var core = require('../services/core');
var sqliteService = require('../services/sqlite');
var mongoService = require('../services/mongodb');

function preCheck(req, res) {
    var reqData = null;
    try {
        reqData = JSON.parse(req.body.data);
    } catch (e) {
        console.error(e);
        res.json({errCode: 1, errMsg: '请求参数有误'});
        return false;
    }
    if (reqData.outline && reqData.word && reqData.phonetic && reqData.explains && reqData.explains.length > 0) {
    } else {
        res.json({errCode: 1, errMsg: '请求参数有误'});
        return false;
    }
    return reqData;
}

exports.add = function (req, res) {
    //validate
    var reqData = preCheck(req, res);
    if(!reqData) return;
    //add to memory
    //todo
    res.json({errCode: 1, errMsg: '代码还没写完'});
};

exports.save = function (req, res) {
    //validate
    var reqData = preCheck(req, res);
    if(!reqData) return;
    //save to memory
    core.save(reqData.word, reqData);
    //save to sqlite if exists
    if (config.store.database.dbFile && fs.existsSync(process.cwd() + config.store.database.dbFile)) {
        sqliteService.saveWord(reqData.word, reqData, function (err) {
            if (err) {
                console.error(err);
                console.log(reqData);
                sendResponse({errCode: 1, errMsg: '数据文件服务出错'});
            } else {
                sendResponse({errCode: 0});
            }
        });
    } else {
        if (config.store.target === 'sqlite') {
            res.json({errCode: 1, errMsg: 'Sqlite数据库配置有误'})
        }
    }

    //save to mongodb if has connection
    var logError = false;
    if (config.store.target === 'mongodb') {
        logError = true;
        mongoService.saveWord(reqData.word, reqData, function (err) {
            if (err && logError) {
                console.error(err);
                console.log(reqData);
                sendResponse({errCode: 1, errMsg: '数据库服务出错'});
            } else {
                sendResponse({errCode: 0});
            }
        });
    }

    var sent = false;
    function sendResponse(json) {
        if (!sent) {
            sent = true;
            res.json(json);
        }
    }
};

exports.export = function (req, res) {
    if (req.query.type === 'json') {
        res.setHeader("Content-Disposition", "attachment; filename=dict.json");
        var dict = core.dict();
        res.json(dict);
    } else {
        var path = process.cwd() + config.store.database.dbFile;
        if (fs.existsSync(path)) {
            res.setHeader("Content-Disposition", "attachment; filename=dict.db3");
            res.write(fs.readFileSync(path));
            res.end();
        } else {
            res.send('No Such File');
        }
    }
};